# -*- coding: utf-8 -*-
"""
Created on Tue Aug 28 09:13:09 2018

@author: Who

 壹块硬币
 http://www.yikuaiyingbi.com/

"""

import requests
import re
from cs import day
from bs4 import BeautifulSoup
from WriteData import writedata
from Tk import genearteMD5


def get_html_text(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
    }
    try:
        r = requests.get(url, timeout=30, headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except Exception as e:
        print(e)
        return None


def get_dates_xw(url):
    text = get_html_text(url)
    if not text:
        return None
    regex = re.compile(r'<b class="media-main-left-news-info-p-b">[\s\S]*?(\d{2}-\d{2}) \d{2}:\d{2}</b>')
    dates = re.findall(regex, text)
    return dates


def get_dates_kx():
    dates = []
    a = 1
    while a < 100:
        url = 'http://www.yikuaiyingbi.com/?/newsflash/0/&p={}'
        url = url.format(a)
        print('---- 壹块硬币快讯获取第{}页----'.format(a))
        text = get_html_text(url)
        a += 1
        if not text:
            continue
        soup = BeautifulSoup(text, 'lxml')
        data = soup.select('.time1')
        dates += [date.get_text() for date in data]

    return dates


def count_process_xw():  # 新闻
    d1 = 0
    d2 = 0
    d3 = 0
    d4 = 0
    a = 1
    while a < 200:
        url = 'http://www.yikuaiyingbi.com/?/news/0/&p={}'
        url = url.format(a)
        dates = get_dates_xw(url)
        print('---- 壹块硬币新闻获取第{}页----'.format(a))
        a += 1
        if not dates:
            continue
        for date in dates:
            s = day('2018-' + date)
            if s == 0:
                d1 += 1
            elif s == 1:
                d2 += 1
            elif s == 2:
                d3 += 1
            else:
                d4 += 1

        if d4 > 0:
            break
    return (d1, d2, d3)


def count_process_kx():  # 快讯
    a = 0
    l = []
    dates = get_dates_kx()
    try:
        while 1:
            if dates[a] < dates[a + 1]:
                l.append(a + 1)
            if len(l) == 3:
                break
            a += 1
        d1 = len(dates[:l[0]])
        d2 = len(dates[l[0]:l[1]])
        d3 = len(dates[l[1]:l[2]])
        return (d1, d2, d3)
    except:
        return (0, 0, 0)


def main():
    u = '壹块硬币'
    t1 = count_process_kx()
    t2 = count_process_xw()
    tk = genearteMD5(u)
    D = {tk: {"name": u, "today": t1[0] + t2[0], "yesterday": t1[1] + t2[1], "frontday": t1[2] + t2[2]}}
    writedata(D)
    return D


if __name__ == '__main__':
    print(main())
